package com.horsen.service.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.horsen.common.util.JwtInfo;
import com.horsen.common.util.JwtUtils;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.user.mapper.AdminMapper;
import com.horsen.service.user.model.Admin;
import com.horsen.service.user.model.DTO.LoginDTO;
import com.horsen.service.user.service.AdminService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Horsen
 * @since 2021-05-10
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    /**
     * 查询一个管理员(会员登录)
     *
     * @param loginDTO 登录对象
     * @return JWTToken
     */
    @Override
    public String login(LoginDTO loginDTO) {
        String name = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        // 校验参数
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new HseduException(ResultCodeEnum.PARAM_ERROR);
        }
        // 校验密码
        LambdaQueryWrapper<Admin> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Admin::getName, name)
                .eq(Admin::getPassword, password);
        Admin admin = baseMapper.selectOne(queryWrapper);
        if (admin == null) {
            throw new HseduException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 检验用户是否被禁用
        if (admin.getDisabled()) {
            throw new HseduException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        // 存入token
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(admin.getId());
        jwtInfo.setName(admin.getName());
        jwtInfo.setAvatar(admin.getAvatar());
        jwtInfo.setRoles(admin.getRoles());
        return JwtUtils.getJwtToken(jwtInfo, 24 * 60 * 60 * 1000);
    }
}
